package com.sailorj.itools.common;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;

import com.sailorj.itools.constants.MyState;
import com.sailorj.itools.constants.SailorjConfigConstants;
import com.sailorj.itools.constants.TransApi;
import com.sailorj.itools.utils.Logger;
import org.apache.http.util.TextUtils;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class Translate {

    /**
     * @param event action
     * @param to 翻译成什么 "en" 英语 ； "zh"  中文
     */
    public static String translateAction(AnActionEvent event, String to) {

        Logger.init(SailorjConfigConstants.title, Logger.DEBUG);

        //获取编辑器
        Editor mEditor = event.getData(PlatformDataKeys.EDITOR);
        if (mEditor == null) {
            Logger.info("编辑器获取失败");
            return null;
        }

        //获取选择器：描述光标选中的文本段
        SelectionModel model = mEditor.getSelectionModel();
        String selectText = model.getSelectedText();
        if (TextUtils.isEmpty(selectText)) {
            Logger.info("未选中文字");
            return null;
        }
        String result = "";
        try {
            result = TransApi.getTransResult(selectText, "auto", to, MyState.getInstance().getConfig());
            System.out.println("翻译返回：" + result);
            Gson gson = new Gson();
            Map<String, JsonObject> transResult = new HashMap<>();
            transResult = gson.fromJson(result, transResult.getClass());

            //获取翻译结果
            JsonArray Jarray = JsonParser.parseString(String.valueOf(transResult.get("trans_result"))).getAsJsonArray();
            JsonObject returnData = JsonParser.parseString(Jarray.get(0).toString()).getAsJsonObject();
            System.out.println(returnData);
            String transQuery = returnData.get("dst").toString();
            //解码
            transQuery = URLDecoder.decode(transQuery, "utf-8").replaceAll("\"", "");
            Logger.showPopupWindow(mEditor, transQuery);
            return transQuery;
        } catch (Exception ex) {
            Logger.showPopupWindow(mEditor, "翻译api返回：" + result + ", 异常：" + ex.getMessage());
            ex.printStackTrace();
        }
        return null;
    }
}
